package com.dxy.yesas2020goals.study.partone.disignpattern.cmdpattern.ftp;

import java.io.*;

/** 文件名过滤器 */
public class ListFilter implements FilenameFilter {
	protected String nameFilter = "";
	protected String extFilter = "";
	protected boolean hasDot = false;

	/**
	 * 构造函数
	 * <p>
	 * 如果有“.”则按文件名和扩展名两部分算， 最后一个点前面的点看成文件名部分
	 */
	public ListFilter(String fstr) {
		// 处理 fstr
		int ls = fstr.length();
		char c, status = '+'; // 'e'=ext, 'w'=wait, ' '=del

		for (int i = 0; i < ls; i++) {
			c = fstr.charAt(i);

			if (status == '+' && c != '.')
				nameFilter += c;
			else if ((status == 'e' || status == 'w') && c != '.')
				extFilter += c;

			if (c == '*')
				status = ' ';
			else if (c == '.') {
				hasDot = true;
				if (status == 'w') // 文件名带点
					nameFilter += extFilter;

				if (status == ' ')
					status = 'e'; // 前面已经有了'*'，不需考虑是否是文件名的点
				else
					status = 'w'; // 此点有可能是文件名的点
				extFilter = ".";
			}
		}
	}

	public boolean accept(File dir, String name) {
		if (hasDot) {
			int ext_pos = name.lastIndexOf('.');
			if (ext_pos < 0)
				return pass(nameFilter, name) && pass(extFilter, ".");
			else
				return pass(nameFilter, name.substring(0, ext_pos)) && pass(extFilter, name.substring(ext_pos));
		} else
			return pass(nameFilter, name);
	}

	protected boolean pass(String fstr, String str) {
		int lfs = fstr.length();
		int ls = str.length();

		if (lfs == 0)
			return (ls == 0);

		if (fstr.charAt(lfs - 1) == '*')
			lfs--;
		else if (ls > lfs)
			return false;

		if (ls < lfs)
			return false;

		for (int i = 0; i < lfs; i++) {
			if (fstr.charAt(i) == '?')
				continue;
			else if (fstr.charAt(i) == '*')
				break;
			else if (Character.toLowerCase(fstr.charAt(i)) != Character.toLowerCase(str.charAt(i)))
				return false;
		}

		return true;
	}
}
